<template>
  <div>
    <div v-if="todo.loading">正在加载中。。。</div>
    <div v-else>{{ todo.result?.title }}</div>
    <div v-if="post.loading">正在加载中。。。</div>
    <div v-else>{{ post.result?.body }}</div>
    <h1>{{ msg }}</h1>
    <h1>{{ count }}</h1>
    <button @click="count++">add</button>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, toRefs, watch, watchEffect } from 'vue'
import useURLLoader from '../hooks/useURLLoader'

interface PostProps {
  userId: number;
  id: number;
  title: string;
  body: string;
}

interface TodoProps {
  userId: number;
  id: number;
  title: string;
  completed: string;
}
export default defineComponent({
  name: 'HelloWorld',
  props: { 
    msg: {
      type: String,
      // default:"",
      required: true
    }
  },
  watch: {
    // msg(curr, old) {
    //   console.log(`watch- msg \n curr:${curr}\nold:${old}`)
    // },
  },
  setup(props) {
    const count = ref(0)
    const stop = watchEffect(() => {
      console.log('props effect', props.msg)
      console.log('count', count.value)
    })
    watch(count, (newValue, oldValue) => {
      //传入某个响应式对象，来监听变化
      console.log(`watch- count \nnewValue:${newValue}\noldValue:${oldValue}`)
    })
    const { msg } = toRefs(props)
    watch(msg, (newValue, oldValue) => {
      //不能直接用props.msg，不是响应式对象，需用toRefs转换
      console.log(`watch- msg1 \nnewValue:${newValue}\noldValue:${oldValue}`)
    })
    watch(
      () => props.msg,
      (newValue, oldValue) => {
        //getter  用函数返回的方式
        console.log(`watch- msg2 \nnewValue:${newValue}\noldValue:${oldValue}`)
      }
    )
    watch([() => props.msg, count], (newValue, oldValue) => {
      //watch多个值可传入数组，返回数组一一对应
      console.log('watch- 多个值')
      console.log(newValue)
      console.log(oldValue)
    })
    const todo = useURLLoader<TodoProps>(
      'https://jsonplaceholder.typicode.com/todos/1'
    )
    const post = useURLLoader<PostProps>(
      'https://jsonplaceholder.typicode.com/posts/1'
    )
    setTimeout(() => {
      stop() //3s以后销毁effect
    }, 3000)
    return {
      count,
      todo,
      post
    }
  },
  methods: {
    // add: msgs => {
    //   this.msg = Number.parseInt(msgs)++
    // },
  }
})
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
li {
  display: inline-block;
  margin: 0 10px;
}
a {
  color: #42b983;
}
</style>
